//
//  WBRefreshControl.swift
//  0829-Weibo
//
//  Created by 毕仲阳 on 16/9/5.
//  Copyright © 2016年 mycompany. All rights reserved.
//

import UIKit
///定义刷新控件的状态
enum WBRefreshStatus: String{
    case normal = "normal"//默认状态
    case pulling = "pulling"//松手刷新
    case refreshing = "refreshing"//刷新
}

private let WBRefreshControlH:CGFloat = 50
class WBRefreshControl: UIControl {
    //记录刷新状态
    var refreshState:WBRefreshStatus = WBRefreshStatus.normal{
        didSet{
            switch refreshState {
            case .pulling:
                UIView.animate(withDuration: 0.25, animations: { 
                    self.arrowIcon.transform = CGAffineTransform.init(rotationAngle: CGFloat(M_PI))
                })
                self.messageLabel.text = "松手更新"
            case .normal:
                self.indicatorView.stopAnimating()
                self.arrowIcon.isHidden = false
                UIView.animate(withDuration: 0.25, animations: { 
                    self.arrowIcon.transform = CGAffineTransform.identity
                })
                self.messageLabel.text = "下拉刷新"
                if oldValue == .refreshing{
                   UIView.animate(withDuration: 0.25, animations: { 
                    var inset = self.scrollView!.contentInset
                    inset.top -= WBRefreshControlH
                    self.scrollView?.contentInset = inset
                   })
                }
            case .refreshing:
                self.arrowIcon.isHidden = true
                self.indicatorView.startAnimating()
                self.messageLabel.text = "正在更新"
                UIView.animate(withDuration: 0.25, animations: {
                    var inset = self.scrollView!.contentInset
                    inset.top += WBRefreshControlH
                    self.scrollView!.contentInset = inset
                })
                sendActions(for: UIControlEvents.valueChanged)
            }
        }
    }
    //记录父控制器
    weak var scrollView:UIScrollView?
    func endRefreshing(){
        self.refreshState = .normal
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
     func setUI()
     {
        
        backgroundColor = UIColor.yellow
        frame.size = CGSize(width: WBScreenW, height: WBRefreshControlH)
        frame.origin.y = -WBRefreshControlH
        
        addSubview(arrowIcon)
        addSubview(messageLabel)
        addSubview(indicatorView)
        arrowIcon.snp_makeConstraints { (make)->Void in
            make.centerX.equalTo(self)
            make.centerY.equalTo(self)
        }
        messageLabel.snp_makeConstraints { (make)->Void in
            make.leading.equalTo(arrowIcon.snp_trailing)
            make.centerY.equalTo(arrowIcon)
        }
        indicatorView.snp_makeConstraints { (make)->Void in
            make.center.equalTo(arrowIcon)
        }
        
    }
    
    override func willMove(toSuperview newSuperview: UIView?) {
        //print(newSuperview)
        if newSuperview is UIScrollView{
            self.scrollView = newSuperview as? UIScrollView
            self.scrollView?.addObserver(self, forKeyPath: "contentOffset", options: [.new,.old], context: nil)
        }
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        //print( self.scrollView?.contentOffset)
        //print(self.scrollView?.contentInset.top)
        //print(self.scrollView?.contentInset.bottom)
        //判断下拉刷新的三种状态
        let contentInsetTop:CGFloat = self.scrollView!.contentInset.top
        let conditionValue = -contentInsetTop - WBRefreshControlH
        
        if scrollView!.isDragging{
            if refreshState == .normal && self.scrollView!.contentOffset.y <= conditionValue{
                refreshState = .pulling
            }else if refreshState == .pulling && self.scrollView!.contentOffset.y > conditionValue{
                refreshState = .refreshing
            }
        }else
        {
            if refreshState == .pulling{
                refreshState = .refreshing
            }
        }
    }
    //移除观察者
    deinit {
        self.scrollView?.removeObserver(self, forKeyPath: "contenOffset")
    }
    //懒加载控件
    lazy var arrowIcon : UIImageView = UIImageView(image: #imageLiteral(resourceName: "tableview_pull_refresh"))
    lazy var messageLabel : UILabel = {
        let label = UILabel(textColor: UIColor.darkGray, fontSize: 12)
        label.text = "准备加载"
        label.sizeToFit()
        return label
    }()
    private lazy var indicatorView :UIActivityIndicatorView = {
        let indicView = UIActivityIndicatorView()
        indicView.color = UIColor.black
        return indicView
    }()

}
